<?php
/**
 * User: zhangligang
 * Email: tzhang2450@163.com
 * Date: 2018/7/27
 * Time: 上午6:47
 */

namespace App\Services;


use App\Models\Apart;
use App\Models\Program;
use App\Models\ProgramApart;
use App\Models\ProgramUser;
use App\Models\Teacher;
use App\Models\User;
use App\Models\UserApart;

class ProgramService extends Service
{

    public static function getProgramList($limit, $offset, $order, $option = [])
    {
        $query = Program::where('status', '>', 0);
        if (count($option) && count($option['query'])) {
            foreach ($option['query'] as $search) {
                $query = $query->where($search['key'], $search['operator'], $search['value']);
            }
        }
        $total = $query->count();
        $programs = $query->orderBy('id', $order)->limit($limit)->offset($offset)->get();
        $data = [];
        foreach ($programs as $program) {
            $data[] = [
                'id' => $program->id,
                'title' => $program->title,
                'state' => $program->state,
                'status' => $program->status,
                'effective_time' => $program->start_at .' ~ '. $program->end_at,
                'apply_time' => $program->apply_start_at .' ~ '. $program->apply_end_at
            ];
        }

        return [
            'total' => $total,
            'rows' => $data,
            'limit' => $limit,
            'offset' => $offset,
            'page' => ceil($total / $limit),
            'pageNumber' => $offset / $limit + 1
        ];
    }

    public static function getProgramDetail($id)
    {
        $program = Program::where('id', $id)->first();

        if (!$program) {
            return [];
        }
        return [
            'data' => [
                'id' => $program->id,
                'title' => $program->title,
                'state' => $program->state,
                'start_at' => $program->start_at,
                'end_at' => $program->end_at,
                'apply_start_at' => $program->apply_start_at,
                'apply_end_at' => $program->apply_end_at,
                'check_start_at' => $program->check_start_at,
                'check_end_at' => $program->check_end_at,
                'desc' => $program->desc
            ]
        ];
    }

    public static function saveProgram($data)
    {
        $program = new Program();
        if (array_key_exists('id', $data) && $data['id']) {
            $program = Program::where('id', $data['id'])->first();
        } else {
            $program->created_at = date('Y-m-d H:i:s', time());
        }
        foreach ($data as $key => $value) {
            $program->$key = $value;
        }
        $program->updated_at = date('Y-m-d H:i:s', time());
        $program->save();
    }

    public static function deleteProgram($id)
    {
        $program = Program::where('id', $id)->first();

        $program->status = 0;
        $program->updated_at = date('Y-m-d H:i:s', time());
        $program->save();
        $programAparts = ProgramApart::where('program_id', $program->id)->get();
        foreach ($programAparts as $programApart) {
            $apart = Apart::where('id', $programApart->apart_id)->first();
            $apart->status = 1;
            $apart->is_program = 0;
            $apart->updated_at = date('Y-m-d H:i:s', time());
            $apart->save();
        }
        ProgramApart::where('program_id', $program->id)->delete();
        ProgramUser::where('program_id', $program->id)->delete();
        UserApart::where('program_id', $program->id)->delete();

    }

    public static function addProgramAparts($id, $data)
    {
        foreach ($data as $value) {
            $programApart = new ProgramApart();
            $programApart->program_id = $id;
            $programApart->apart_id = $value['id'];
            $programApart->apart_name = $value['name'];
            $programApart->status = 1;
            $programApart->created_at = date('Y-m-d H:i:s', time());
            $programApart->updated_at = date('Y-m-d H:i:s', time());
            $programApart->save();
            $apart = Apart::where('id', $value['id'])->first();
            $apart->status = 2;
            $apart->is_program = 1;
            $apart->updated_at = date('Y-m-d H:i:s', time());
            $apart->save();
        }
    }

    public static function getProgramUserList($programId, $limit, $offset, $order)
    {
        $query = ProgramUser::select(['at_program_user.id', 'at_program_user.realname', 'at_program_user.status', 'at_program_user.start_at', 'at_program_user.end_at', 'at_teacher.score'])->leftJoin('at_teacher', 'at_teacher.user_id', 'at_program_user.user_id')->where('at_program_user.program_id', $programId);
        $total = $query->count();
        $programUsers = $query->orderBy('at_teacher.score', 'desc')->orderBy('at_program_user.id', $order)->limit($limit)->offset($offset)->get();
        $data = [];
        foreach ($programUsers as $programUser) {
            $data[] = [
                'id' => $programUser->id,
                'realname' => $programUser->realname,
                'score' => $programUser->score,
                'status' => $programUser->status,
                'start_end_time' => $programUser->start_at .' - '. $programUser->end_at
            ];
        }

        return [
            'total' => $total,
            'rows' => $data,
            'limit' => $limit,
            'offset' => $offset,
            'page' => ceil($total / $limit),
            'pageNumber' => $offset / $limit + 1
        ];
    }


    public static function getProgramUserApartList($programId, $limit, $offset, $order)
    {
        $query = UserApart::where('program_id', $programId);
        $total = $query->count();
        $userAparts = $query->orderBy('id', $order)->limit($limit)->offset($offset)->get();
        $data = [];
        foreach ($userAparts as $userApart) {
            $programUser = ProgramUser::where('program_id', $programId)->where('user_id', $userApart->user_id)->first();
            $data[] = [
                'id' => $userApart->id,
                'realname' => $userApart->realname,
                'is_selected' => $userApart->apart_id > 0,
                'apart_id' => $userApart->apart_id,
                'apart_name' => $userApart->apart_name,
                'start_end_time' => local_date($programUser->start_at, 'Y-m-d H:i') . ' ~ ' . local_date($programUser->end_at, 'Y-m-d H:i'),
                'status' => $userApart->status,
                'created_at' => local_date($userApart->created_at)
            ];
        }

        return [
            'total' => $total,
            'rows' => $data,
            'limit' => $limit,
            'offset' => $offset,
            'page' => ceil($total / $limit),
            'pageNumber' => $offset / $limit + 1
        ];
    }

    public static function changeProgramUserStatus($data)
    {
        $startEndTime = [];
        if ($data['status'] == 2) {
            $startEndTime = explode(' ~ ', $data['start_end_time']);
        }
        if (is_numeric($data['id'])) {
            $programUser = ProgramUser::where('id', $data['id'])->first();
            $programUser->status = $data['status'];
            if (array_key_exists('status', $data) && $data['status'] == 2) {
                $programUser->start_at = $startEndTime[0];
                $programUser->end_at = $startEndTime[1];
            }
            $programUser->updated_at = date('Y-m-d H:i:s', time());
            $programUser->save();
        } else {
            $ids = explode(',', rtrim($data['id'], ','));
            ProgramUser::whereIn('id', $ids)->update(['status' => $data['status'], 'start_at' => $startEndTime[0], 'end_at' => $startEndTime[1], 'updated_at' => date('Y-m-d H:i:s', time())]);
        }

    }

    public static function apply($programId, $userId)
    {
        $user = User::where('id', $userId)->first();
        $programUser = new ProgramUser();
        $programUser->program_id = $programId;
        $programUser->user_id = $userId;
        $programUser->realname = $user->realname;
        $programUser->start_at = '0000-00-00 00:00:00';
        $programUser->end_at = '0000-00-00 00:00:00';
        $programUser->state = 0;
        $programUser->status = 0;
        $programUser->created_at = date('Y-m-d H:i:s', time());
        $programUser->updated_at = date('Y-m-d H:i:s', time());
        $programUser->save();
    }
}